//
//  ViewController.swift
//  eat_known
//
//  Created by 心情 on 2018/7/26.
//  Copyright © 2018年 心情. All rights reserved.
//

import UIKit
import Kingfisher
import SnapKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
    
    var searchbar: UISearchBar
    var tableView: UITableView
    var foods: [Food] = Array()

    required init?(coder aDecoder: NSCoder) {
        
        tableView = UITableView()
        searchbar = UISearchBar()
        
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.addSubview(tableView)
        tableView.register(FoodListCell.self, forCellReuseIdentifier: FoodListCell.className())
        tableView.rowHeight = 100
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .onDrag

        searchbar.delegate = self
        searchbar.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: 40)
        searchbar.becomeFirstResponder()
        tableView.tableHeaderView = searchbar
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(#selector(search(_:)), with: searchText, afterDelay: 1)
    }
    
    @objc
    func search(_ text: String) {
        if text.count == 0 {
            return
        }
        foods.removeAll()
        let group = DispatchGroup.init()
        group.enter()
        BabyTreeRequest.start(keyword: text) { (foods, error) in
            if foods != nil {
                self.foods += foods!
            }
            group.leave()
        }
        group.enter()
        LadyBirdRequest.start(keyword: text) { (foods, error) in
            if foods != nil {
                self.foods += foods!
            }
            group.leave()
        }
        
        group.enter()
        AlipayRequest.start(keyword: text) { (foods, error) in
            if foods != nil {
                self.foods += foods!
            }
            group.leave()
        }


        
        group.notify(queue: DispatchQueue.main) {
            self.foods.sort(by: { (one, two) -> Bool in
                return one.name == text
            })
            self.tableView.reloadData()
        }
        
    }
    
//MARK:- tableview delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return foods.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FoodListCell.className(), for: indexPath) as! FoodListCell
        let food = foods[indexPath.row]
        cell.titleLabel.text = food.name! + "(\(food.source.rawValue))"
        cell.subTitleLabel.text = food.desc
        cell.iconView.kf.setImage(with: food.imageURL)
        cell.buttonGroupView.phases = food.phaseList
        return cell
    }


}

